package com.xiaohu.transfrom;

import com.xiaohu.bean.WaterSensor;
import org.apache.flink.api.java.functions.KeySelector;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.datastream.KeyedStream;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;

/*
    简单聚合算子，只能作用在keyBy之后的KeyedStream类型上
    sum|max|min|maxBy|minBy
 */
public class SimpleAggregateDemo {
    public static void main(String[] args) throws Exception {
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();

        env.setParallelism(1);

        DataStreamSource<WaterSensor> senorDS = env.fromElements(
                new WaterSensor("s1", 1L, 5),
                new WaterSensor("s2", 2L, 2),
                new WaterSensor("s3", 3L, 3),
                new WaterSensor("s1", 4L, 4),
                new WaterSensor("s2", 5L, 5),
                new WaterSensor("s1", 6L, 6)
        );

        KeyedStream<WaterSensor, String> sensorKS = senorDS.keyBy(new KeySelector<WaterSensor, String>() {
            @Override
            public String getKey(WaterSensor value) throws Exception {
                return value.getId();
            }
        });


        //sum聚合算子
        //传位置索引适用于Tuple类型
//        SingleOutputStreamOperator<WaterSensor> res1 = sensorKS.sum(2);
        //传 自定义类型的字段值
//        SingleOutputStreamOperator<WaterSensor> res1 = sensorKS.sum("vc");
//        res1.print();

        //max聚合算子1
        SingleOutputStreamOperator<WaterSensor> res2 = sensorKS.max("vc");
        res2.print();

        //maxBy会取最大比较字段的，以及其他非比较字段的值
//        SingleOutputStreamOperator<WaterSensor> res3 = sensorKS.maxBy("vc");
//        res3.print();

        env.execute();
    }
}
